package com.ruoyi.sentinel.controller;

import cn.hutool.core.date.DateUtil;
import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.ruoyi.sentinel.handler.MyBlockHandler;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;

@RestController
public class SentinelController {
    private static int i = 0;
    private static List<String> correct = new ArrayList();
    private static List<String> all = new ArrayList<>();

    @GetMapping
    public String say() {
        return "hello " + DateUtil.format(new Date(), "yyyy-MM-dd HH:mm:ss");
    }

    @GetMapping("/a")
    public String a() {
        return "hello from a ................." + DateUtil.format(new Date(), "yyyy-MM-dd HH:mm:ss");
    }

    /*RT*/
    @GetMapping("/c")
    public String c() throws Exception {
        String startTime = DateUtil.format(new Date(), "yyyy-MM-dd HH:mm:ss");
        TimeUnit.SECONDS.sleep(2);
        String endTime = DateUtil.format(new Date(), "yyyy-MM-dd HH:mm:ss");
        return "from " + startTime + " to " + endTime;
    }

    /*比例异常*/
    @GetMapping("/d")
    public String d() {
        i++;
        String name = Thread.currentThread().getName();
        all.add(name);
        if (i % 2 == 0) {
            int k = i / 0;
        }
        correct.add(name);
        return "all:" + all.size() + "\nerror:" + (all.size() - correct.size());
    }

    @GetMapping("/sr")
    @SentinelResource(value = "sr", blockHandler = "blockHandler")
    public String sr(String p1, String p2) {
        return "test SentinelResource";
    }

    public String blockHandler(String p1, String p2, BlockException e) {
        return JSONObject.toJSONString(e, SerializerFeature.PrettyFormat);
    }

    @GetMapping("/e")
    @SentinelResource(value = "e", blockHandlerClass = MyBlockHandler.class,blockHandler = "handleException")
    public String e() {
        return "hello e";
    }
}
